package com.mvvm.start.base

import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build

import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.multidex.MultiDexApplication

import com.mvvm.start.base.app.ActivityLifecycleCallbacksImpl
import com.mvvm.start.base.app.LoadModuleProxy
import com.mvvm.start.base.utils.*

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch

import kotlin.system.measureTimeMillis


/**
 * @author
 * @功能:
 * @Creat 12/10/20 4:51 PM
 * @Compony 465008238@qq.com
 */
open class BaseApplication : MultiDexApplication() {
    private val mCoroutineScope by lazy(mode = LazyThreadSafetyMode.NONE) { MainScope() }
    private val mLoadModuleProxy by lazy(mode = LazyThreadSafetyMode.NONE) { LoadModuleProxy() }

    companion object {
        @SuppressLint("StaticFieldLeak")
        lateinit var application: BaseApplication

        @SuppressLint("StaticFieldLeak")
        lateinit var context: Context
        var isGrayTheme = false //设置全局灰度
        var isTestUrl = false
    }

    init {
        LogUtils.init("LMY")
    }

    lateinit var notificationManager: NotificationManager
    lateinit var notificationBuilder: NotificationCompat.Builder

    override fun attachBaseContext(base: Context) {
        super.attachBaseContext(base)
        application = this
        context = base
        isTestUrl = (SPUtils.getInstance(context)
            .getSharedPreference(ConstantUtils.OPEN_TEST_URL, false) as Boolean) //是否使用测试服地址
        mLoadModuleProxy.onAttachBaseContext(base)
    }


    override fun onCreate() {
        super.onCreate()
        initActivityLifecycle()
        mLoadModuleProxy.onCreate(this)
        initNotification()
//        if (!BuildConfig.DEBUG) {
//            initException()
//        }
        if ((SPUtils.getInstance(context)
                .getSharedPreference(ConstantUtils.PRIVACY_IS_SHOW, 0) as Int) == 1
        ) {
            initDepends()
        }
    }


    /**
     * 初始化第三方依赖
     */
    fun initDepends() {
        // 开启一个 Default Coroutine 进行初始化不会立即使用的第三方
        mCoroutineScope.launch(Dispatchers.Default) {
            mLoadModuleProxy.initByBackstage()
        }

        // 前台初始化
        val allTimeMillis = measureTimeMillis {
            val depends = mLoadModuleProxy.initByFrontDesk()
            var dependInfo: String
            depends.forEach {
                val dependTimeMillis = measureTimeMillis { dependInfo = it() }
                Log.d("BaseApplication", "initDepends: $dependInfo : $dependTimeMillis ms")
            }
        }
        Log.d("BaseApplication", "初始化完成 $allTimeMillis ms")
    }


    /**
     * 注册Activity的生命监听
     */
    private fun initActivityLifecycle() {
        registerActivityLifecycleCallbacks(ActivityLifecycleCallbacksImpl())
    }


    private fun initNotification() {
        notificationManager =
            context?.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationBuilder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val mChannel =
                NotificationChannel("start", "MVVMStart", NotificationManager.IMPORTANCE_HIGH)
            mChannel.enableVibration(false);   // 设置通知出现时的震动（如果 android 设备支持的话）
            notificationManager.createNotificationChannel(mChannel)
            NotificationCompat.Builder(this, "start")
        } else {
            NotificationCompat.Builder(context)
        }
    }

    /**
     * 全局异常捕获 捕获到异常重启app
     */
    private fun initException() {
        Thread.setDefaultUncaughtExceptionHandler(CrashHandler(this))
    }


    override fun onTerminate() {
        super.onTerminate()
        mLoadModuleProxy.onTerminate(this)
        mCoroutineScope.cancel()
    }
}



